const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const cors = require('cors');

const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
    cors: {
        origin: "*", // 允许任何源
        methods: ["GET", "POST"]
    }
});
const players = {}; // 存储玩家名字

let rooms = {};

function checkWin(board, x, y) {
    const player = board[x][y]?board[x][y].id:'';
    const directions = [
        { x: 1, y: 0 }, // 水平
        { x: 0, y: 1 }, // 垂直
        { x: 1, y: 1 }, // 右下斜
        { x: 1, y: -1 }, // 右上斜
    ];

    for (const dir of directions) {
        let count = 1; // 包括这个棋子自身

        // 向一个方向检查
        for (let d = 1; d < 5; d++) {
            const nx = x + dir.x * d;
            const ny = y + dir.y * d;
            const bid =  board[nx][ny]?board[nx][ny].id:'';
            if (nx < 0 || ny < 0 || nx >= 15 || ny >= 15 || bid !== player) break;
            count++;
        }

        // 向相反方向检查
        for (let d = 1; d < 5; d++) {
            const nx = x - dir.x * d;
            const ny = y - dir.y * d;
            const bid =  board[nx][ny]?board[nx][ny].id:'';
            if (nx < 0 || ny < 0 || nx >= 15 || ny >= 15 || bid !== player) break;
            count++;
        }

        // 检查胜利
        if (count >= 5) {
            return true; // 有胜利
        }
    }
    return false; // 没有胜利
}

io.on('connection', (socket) => {
    socket.on('joinRoom', ({ room, playerName }) => {
        socket.join(room);

        if (!rooms[room]) {
            rooms[room] = { players: [], playerNames:[], board: Array(15).fill().map(() => Array(15).fill(null)) };
        }

        rooms[room].players.push(socket.id);
        rooms[room].playerNames.push(playerName);
        players[socket.id] = playerName; // 记录玩家名字

        if (rooms[room].players.length === 1) {
            io.to(room).emit('oneTip', room);
        }else if (rooms[room].players.length === 2) {
            io.to(room).emit('startGame', { board: rooms[room].board, playerNames: rooms[room].playerNames, players: rooms[room].players });
        }else if (rooms[room].players.length > 2) {
            io.to(room).emit('gameTip',room);
        }
    });
    
    socket.on('makeMove', ({ room, x, y, currentId }) => {
        const board = rooms[room].board;

        if (!board[x][y]) {
            let sumArr = board.reduce((pre, cur) => pre.concat(cur));
            let idnum = sumArr.filter(item => item !== null).length;
            board[x][y] = {id: socket.id,step: idnum+1}; // 落子
            io.to(room).emit('updateBoard', {board,currentId});

            // 检查胜利
            if (checkWin(board, x, y)) {
                io.to(room).emit('gameOver', socket.id); // 发送游戏结束信息
            }
        }
    });

    socket.on('restartGame', (room) => {
        if (rooms[room]) {
            rooms[room].board = Array(15).fill().map(() => Array(15).fill(null)); // 重置棋盘
            io.to(room).emit('resetBoard', rooms[room].board); // 向所有玩家发送重置消息
        }
    });

    socket.on('disconnect', () => {
        for (const room in rooms) {
            rooms[room].players = rooms[room].players.filter(id => id !== socket.id);
            if (rooms[room].players.length === 0) {
                delete rooms[room];
            }
        }
    });
});

server.listen(3001, () => {
    console.log('Server is running on http://localhost:3001');
});